package com.xfcycle.zebrabikegp.util;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 获取当前设备唯一序列号
 * Created by xFcycle on 2017/4/28.
 */

public class GetUUIDUtil {

    private Context context;
    private static GetUUIDUtil getUUIDUtil;

    private GetUUIDUtil(Context context) {
        this.context = context;
    }

    public static GetUUIDUtil getInstance(Context context) {
        synchronized (GetUUIDUtil.class) {
            if (null == getUUIDUtil || !context.equals(getUUIDUtil.context)) {
                getUUIDUtil = new GetUUIDUtil(context);
            }
        }
        return getUUIDUtil;
    }

    public String getDevicesUUIDByMD5() {
        List<String> resultList = new ArrayList<>();
        StringBuffer center_id = new StringBuffer();

        try {
            //获取IMEI，仅对手机有效，需要read_phone_state权限
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (null != telephonyManager) {
                resultList.add(telephonyManager.getDeviceId());
            }

            //获取Pseudo_uid，通过各种硬件设备序列号长度算出
            resultList.add("707" + Build.BOARD.length() % 10 +
                    Build.BRAND.length() % 10 +
                    Build.DEVICE.length() % 10 +
                    Build.BOOTLOADER.length() % 10 +
                    Build.DISPLAY.length() % 10 +
                    Build.HOST.length() % 10 +
                    Build.MANUFACTURER.length() % 10 +
                    Build.USER.length() % 10 +
                    Build.TAGS.length() % 10 +
                    Build.TYPE.length() % 10 +
                    Build.PRODUCT.length() % 10 +
                    Build.MODEL.length() % 10);

            //获取The android ID，如果手机被root过，那么可以被改变,通常被认为不可信
            resultList.add(Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));

            //获取有蓝牙设备的MAC地址，需要BLUETOOTH权限
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (null != bluetoothAdapter) {
                resultList.add(bluetoothAdapter.getAddress());
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            for (String param: resultList) {
                if(null != param){
                    center_id.append(param);
                }
            }
        }
        return EncryptStringUtil.getMd5(center_id.toString());
    }

    /**
     * 生成一个UUID用于数据库使用
     * @return 返回得到的UUID
     */
    public static String getDatabaseUUID(){
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
